<?php
namespace app\web\controller;

use app\model\Theme; 

class ExclusiveImage extends Base
{
    public function Exclusive_image()
    {
global $_G,$_S,$_C,$_P;
$themeid = intval($_P['themeid']);
if($themeid <= 0){
    $themeid = Theme::getDefaultThemenew();
}
$theme = Theme::getThemeById($themeid);
$theme_bengin_time = $theme['begintime'];
$theme_end_time = $theme['endtime'];

$setting = db_find("SELECT * FROM ".tablename('uni_account_modules')." WHERE module=:module  order by uniacid asc", array(':module' => MODULE_NAME));
$systems = !empty($setting['settings']) ? xunserializer($setting['settings']) : array();
$system = $systems;

$do = 'exclusive_image';
$op = isset($_P['op'])?$_P['op']:'display';
$sort = intval($_P['sort']);
$action = $_P['action'];
$id = isset($_P['id'])?$_P['id']:'';
$companylists = db_select("SELECT id,name FROM  ".tablename(t_shangjia)." ORDER BY id ASC");
$wlist = db_select("SELECT uid,username FROM  ".tablename(t_worker)." ORDER BY uid ASC");

switch ($op){
    case 'display':     //展示
        $condition=" WHERE 1=1";

        //状态
        $status = $_P['status'];
        if ($status){
            $condition .= " AND i.status = $status";
        }

        $company = $_P['company'];
        if ($company){
            $condition .= " AND i.company = $company";
        }

        $salesman = $_P['salesman'];
        if ($salesman){
            $condition .= " AND i.salesman = $salesman";
        }

        $designer = $_P['designer'];
        if ($designer){
            $condition .= " AND i.designer = $designer";
        }

        $search_data = $_P['search_data'];
        if ($search_data){
            $condition .= " AND i.title LIKE '".$search_data."'";
        }

        $page_index = max(1,intval($_P['page']));
        $page_size = 20;
        $page_start = ($page_index-1)*$page_size;
        $condition .= " ORDER BY i.id DESC, i.status asc ";
        if ($page_size) {
            $condition .= "LIMIT ".$page_start.",".$page_size;
        }

        $total = db_find("SELECT COUNT(*) as cnt FROM ".tablename('exclusive_image')." AS i ");
        $total = $total['cnt'];



        $sql = " SELECT i.*,t.username as salesman_name,t1.username as designer_name,s.name company_name  FROM ".tablename('exclusive_image')." as i ".
            " left join ".tablename(t_worker)." as t on i.salesman=t.uid and t.themeid =".$themeid.
            " left join ".tablename(t_worker)." as t1 on i.designer=t1.uid and t1.themeid=".$themeid.
            " left join ".tablename(t_shangjia)." as s on i.company=s.id  ".
              $condition;
        $list =  db_select($sql);
     //GROUP_CONCAT(s.name) company_name   FIND_IN_SET(s.id,i.company)
        $page_total = $total;
        $pager = pagination($page_total,$page_index,$page_size);
        $return_clicent = get_defined_vars();
return view('/exclusive_image', $return_clicent);
        break;
    case  'add':        //添加入库
         $return_clicent = get_defined_vars();
return view('/exclusive_image_add', $return_clicent);
    break;
    case  'save':  //提交入库
        //数据验证
        if(empty($_P['img_url'])){
            show_json(0,['msg'=>'请选择专版图片']);
        }

        if(empty($_P['title'])){
            show_json(0,['msg'=>'请输入专版名称']);
        }

        if(!$_P['company']){
            show_json(0,['msg'=>'请选择秀场公司']);
        }

        if(!$_P['salesman']){
            show_json(0,['msg'=>'请选择销售人员']);
        }

        if(!$_P['designer']){
            show_json(0,['msg'=>'请选择设计师']);
        }

        $sql = " select count(*) as cnt from ".tablename('exclusive_image')." where title= "."'".$_P['title']."'"." OR  img_url="."'".$_P['img_url']."'";
        $check_count =  intval(db_find($sql)['cnt']);
        if($check_count>0){
            show_json(0,['msg'=>'名称或图像已存在']);
        }

        $company = $_P['company'];
        $img_url = tomedia($_P['img_url']);

        $affirm_post = $_P['affirm_post'];
        $realtime_search_res = $_P['realtime_search_res'];

        if($affirm_post==0||empty($realtime_search_res)||$_P['old_img_url']<>$_P['img_url']){
            //获取token
            $get_token = self::get_access_token($themeid);
            if(isset($get_token['msg'])){
                show_json(0,['msg'=>$get_token['msg']]);
            }
            $token = $get_token['access_token'];
            //百度图片相似度查询
            $url = 'https://aip.baidubce.com/rest/2.0/realtime_search/same_hq/search?access_token=' . $token;
            $img = file_get_contents($img_url);
            $img = base64_encode($img);
            $bodys = array(
                'image' => $img
            );
            $realtime_search_res = self::request_post($url, $bodys);
            if($realtime_search_res['result_num']>0){
                $exclusive_image = array();
                foreach ($realtime_search_res['result'] as $v){
                    $id = $v['brief'];
                    $image_info =  db_get('exclusive_image', ['id' => $id], ['id','title','img_url']);
                    if($image_info){
                        $image_info['img_url'] = tomedia($image_info['img_url']);
                        $image_info['score'] =  round($v['score'] * 100, 2).'%';
                        $exclusive_image[]  = $image_info;
                    }
                }
                show_json(2,['msg'=>'有'.$realtime_search_res['result_num'].'个相似度图片,如确认提交请再次点击提价按钮',
                                    'data' => $exclusive_image,
                                    'realtime_search_res' => $realtime_search_res,
                                    'old_img_url' => $_P['img_url']
                                 ]);
                }
        }
        //数组转字符串
        $data = [
            'title' => $_P['title'],
            'img_url' =>  $_P['img_url'],
            'company' => $company,
            'salesman' => $_P['salesman'],
            'designer' => $_P['designer'],
            'res_json' => json_encode($realtime_search_res),
            'create_time' => date('Y-m-d H:i:s',time()),
        ];
        $res = $insertid = db_insert('exclusive_image',$data);
        if($res){
            show_json(1,['msg'=>'添加成功']);
        }else{
            show_json(0,['msg'=>'添加失败']);
        }
    break;
    case 'audit':
        if(!$id){
            return_msg('ID不存在');
        }
        $item_sql =  "SELECT i.*,t.username as salesman_name,t1.username as designer_name,s.name as company_name FROM ".tablename('exclusive_image')." as i ".
            " left join ".tablename(t_worker)." as t on i.salesman=t.uid".
            " left join ".tablename(t_worker)." as t1 on i.designer=t1.uid".
            " left join ".tablename(t_shangjia)." as s on i.company = s.id".
            " WHERE i.id = $id";
        $item = db_find($item_sql);
        $exclusive_image = array();
        if($item['res_json']){
            $res_json = json_decode($item['res_json'],true);
            if($res_json['result']){
                foreach ($res_json['result'] as $v){
                    $id = $v['brief'];
                    $image_info =  db_get('exclusive_image', ['id' => $id], ['id','title','img_url']);
                    if($image_info){
                        $image_info['img_url'] = tomedia($image_info['img_url']);
                        $image_info['score'] =  round($v['score'] * 100, 2).'%';
                        $exclusive_image[]  = $image_info;
                    }
                }
            }
        }
        $item['exclusive_image'] = $exclusive_image;
        $item['img_url'] = tomedia($item['img_url']);
        $return_clicent = get_defined_vars();
return view('/exclusive_image_audit', $return_clicent);
        break;
    case 'pass':   //审核通过  同步到百度图片
        if(!$id){
            show_json(0,['msg'=>'ID不存在']);
        }
        $image_info =  db_get('exclusive_image', ['id' => $id], ['id','title','img_url']);
        if(!$image_info){
            show_json(0,['msg'=>'数据不存在']);
        }
        //图片入库
        $get_token = self::get_access_token($themeid);
        if(isset($get_token['msg'])){
            show_json(0,['msg'=>$get_token['msg']]);
        }
        $img_url = tomedia($image_info['img_url']);
        $token = $get_token['access_token'];
        $url = 'https://aip.baidubce.com/rest/2.0/realtime_search/same_hq/add?access_token=' . $token;
        $img = file_get_contents($img_url);
        $img = base64_encode($img);

        $bodys = array(
            'brief' => $id,
            'image' => $img,
            'tags' => $themeid
        );
        $res = self::request_post($url, $bodys);
        if(isset($res['error_code'])){
            show_json(0,['msg'=>$res['error_code'].' '.$res['error_msg']]);
        }
        $update_data['cont_sign'] =$res['cont_sign'];
        $update_data['update_time'] = date('Y-m-d H:i:s',time());
        $update_data['status'] = 1;
        db_update('exclusive_image',$update_data,['id'=>$id]);
        self::insert_record($id,1);
        show_json(1,['msg' => '操作成功']);
    break;

    case 'reject':
        if(!$id){
            show_json(0,['msg'=>'ID不存在']);
        }
        $image_info =  db_get('exclusive_image', ['id' => $id], ['id','title','img_url']);
        if(!$image_info){
            show_json(0,['msg'=>'数据不存在']);
        }

        $update_data['update_time'] = date('Y-m-d H:i:s',time());
        $update_data['status'] = -1;
        db_update('exclusive_image',$update_data,['id'=>$id]);
        self::insert_record($id,2);
        show_json(1,['msg' => '操作成功']);
    break;

    case 'delete':
        if(!$id){
            show_json(0,['msg'=>'ID不存在']);
        }
        $image_info =  db_get('exclusive_image', ['id' => $id], ['id','status']);
        if(!$image_info){
            show_json(0,['msg'=>'数据不存在']);
        }
        if($image_info['status']<>-1||$image_info['status']<>0){
            show_json(0,['msg'=>'数据不可删除']);
        }

         if(db_delete('exclusive_image_log',['exclusive_image_id' => $id])){
             if(db_delete('exclusive_image',['id' => $id])){
                 show_json(1,['msg'=>'删除成功']);
             }else{
                 show_json(0,['msg'=>'信息删除失败']);
             }
         }else{
             show_json(0,['msg'=>'记录删除失败']);
         }
       break;

    case  'up':        //上架
        if(!$id){
            show_json(0,['msg'=>'ID不存在']);
        }
        $image_info =  db_get('exclusive_image', ['id' => $id], ['id','status']);
        if(!$image_info){
            show_json(0,['msg'=>'数据不存在']);
        }
        if($image_info['status']<>-2){
            show_json(0,['msg'=>'数据不可下架']);
        }
        $update_data['update_time'] = date('Y-m-d H:i:s',time());
        $update_data['status'] = 1;
        db_update('exclusive_image',$update_data,['id'=>$id]);
        self::insert_record($id,3);
        show_json(1,['msg' => '操作成功']);
        break;

    case  'down':  //下架
        if(!$id){
            show_json(0,['msg'=>'ID不存在']);
        }
        $image_info =  db_get('exclusive_image', ['id' => $id], ['id','status']);
        if(!$image_info){
            show_json(0,['msg'=>'数据不存在']);
        }
        if($image_info['status']<>1){
            show_json(0,['msg'=>'数据不可下架']);
        }
        $update_data['update_time'] = date('Y-m-d H:i:s',time());
        $update_data['status'] = -2;
        db_update('exclusive_image',$update_data,['id'=>$id]);
        self::insert_record($id,4);
        show_json(1,['msg' => '操作成功']);
        break;

    case 'log':   //操作记录
        if(!$id){
            show_json(0,['msg'=>'ID不存在']);
        }
        $image_info =  db_get('exclusive_image', ['id' => $id], ['id','status']);
        if(!$image_info){
            show_json(0,['msg'=>'数据不存在']);
        }
        $condition = " where exclusive_image_id = $id";
        $page_index = max(1,intval($_P['page']));
        $page_size = 20;
        $page_start = ($page_index-1)*$page_size;
        $condition .= " ORDER BY id DESC";
        if ($page_size) {
            $condition .= "LIMIT ".$page_start.",".$page_size;
        }

        $total = db_find("SELECT COUNT(*) as cnt  FROM ".tablename('exclusive_image_log'));
        $total = $total['cnt'];
        $sql = " SELECT * FROM ".tablename('exclusive_image').$condition;
        $list =  db_select($sql);
        $page_total = $total;
        $pager = pagination($page_total,$page_index,$page_size);
        $return_clicent = get_defined_vars();
return view('/exclusive_image_log', $return_clicent);
        break;
}

//获取token
function get_access_token($themeid){
    global $_G,$_S,$_C,$_P;
    $cachekey = 'baidu'.$_G['mpid'].MODULE_NAME.$themeid;
    $settings = cache_load($cachekey);
    //var_self::dump($settings);
    //存在缓存并且没有过期
    if($settings&&$settings['expiration_time']<time()){
        return $settings;
    }else{
        $apiKey = 'Z0br1xKxMYi2BCepWtS5qGfM';
        $clientSecret = '2CkrIU3UG5IDnG5q9BWQOlSogzFm0KSa';
        $url = 'https://aip.baidubce.com/oauth/2.0/token';
        $post_data['grant_type']  = 'client_credentials';
        $post_data['client_id']   = $apiKey;
        $post_data['client_secret'] = $clientSecret;
        $o = "";
        foreach ( $post_data as $k => $v )
        {
            $o.= "$k=" . urlencode( $v ). "&" ;
        }
        $post_data = substr($o,0,-1);
        $res = self::request_post($url, $post_data);
        if(isset($res['error'])){
             if($res['error_description']=='unknown client id'){
                 return   ['msg'=>'API Key不正确'];
                 exit();
             }
             if($res['error_description']=='Client authentication failed'){
                 return ['msg'=>'Secret Key不正确'];
                 exit();
             }
        }
       // var_self::dump($res);
        //过期时间 当前时间加上有效期减去一分钟 因为请求接口也需要时间
        $cachedata  = [
                'access_token' => $res['access_token'],
                'expiration_time' => time()+$res['expires_in']-60
        ];
        cache_write($cachekey,$cachedata);      //缓存
        return $cachedata;
    }
}
//curl post 提交
function request_post($url = '', $param = '') {
    if (empty($url) || empty($param)) {
        return false;
    }
    $postUrl = $url;
    $curlPost = $param;
    // 初始化curl
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $postUrl);
    curl_setopt($curl, CURLOPT_HEADER, 0);
    // 要求结果为字符串且输出到屏幕上
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
    // post提交方式
    curl_setopt($curl, CURLOPT_POST, 1);
    curl_setopt($curl, CURLOPT_POSTFIELDS, $curlPost);
    // 运行curl
    $re = curl_exec($curl);
    curl_close($curl);
    return  json_decode($re,true);
}

//封装
function insert_record($id,$type){
    switch ($type){
        case 1:
            $type_name = '审核通过';
            break;
        case 2:
            $type_name = '审核未通过';
            break;
        case 3:
            $type_name = '上架';
            break;
        case 4:
            $type_name = '下架';
            break;
        default:
            $type_name = '审核痛哟';
            break;
    }

    $log_data['exclusive_image_id'] = $id;
    $log_data['type'] = $type;    //审核通过
    $log_data['remark'] = $type_name;
    $log_data['admin_name'] = '111';
    $log_data['create_time'] = date('Y-m-d H:i:s',time());
    $insertid = db_insert('exclusive_image_log',$log_data);
}

//操作类型


function is_json($data = '', $assoc = false) {
    $data = json_decode($data, $assoc);
 if (($data && is_object($data)) || (is_array($data) && !empty($data))) {
        return $data;
   }
   return false;
}

function dump($var, $echo=true, $label=null, $strict=true) {
    $label = ($label === null) ? '' : rtrim($label) . ' ';
    if (!$strict) {
        if (ini_get('html_errors')) {
            $output = print_r($var, true);
            $output = "<pre>" . $label . htmlspecialchars($output, ENT_QUOTES) . "</pre>";
        } else {
            $output = $label . print_r($var, true);
        }
    } else {
        ob_start();
        var_self::dump($var);
        $output = ob_get_clean();
        if (!extension_loaded('xdebug')) {
            $output = preg_replace("/]=>(s+)/m", "] => ", $output);
            $output = '<pre>' . $label . htmlspecialchars($output, ENT_QUOTES) . '</pre>';
        }
    }
    if ($echo) {
        echo($output);
        return null;
    }else
        return $output;
}
}
}